package com.leetcode.easy;

/**
 * @Classname MaxProfit
 * @Description 买卖股票的最佳时机
 * @Date 2020/9/22 14:46
 * @Created by zfl
 */
public class MaxProfit {

    /**
     * @param prices
     * @return
     * 买卖股票的最佳时机I
     * 执行用时：1 ms, 在所有 Java 提交中击败了99.01%的用户
     * 内存消耗：39 MB, 在所有 Java 提交中击败了13.96%的用户
     */
    public static int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0) {
            return 0;
        }
        int cost = prices[0];
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            if(prices[i] < cost) {
                cost = prices[i];
            }else if(profit < prices[i] - cost) {
                profit = prices[i] - cost;
            }
        }
        return profit;
    }

    /**
     * @param prices
     * @return
     * 买卖股票的最佳时机II
     * 执行用时：1 ms, 在所有 Java 提交中击败了99.55%的用户
     * 内存消耗：39.1 MB, 在所有 Java 提交中击败了9.27%的用户
     */
    public static int maxProfit2(int[] prices) {
        if(prices == null || prices.length == 0) {
            return 0;
        }
        int cost = prices[0], profit = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            if(prices[i + 1] < prices[i]) {
                if(cost >= 0) {
                    profit += prices[i] - cost;
                    cost = prices[i + 1];
                }
            }
        }
        if(prices[prices.length - 1] > cost) {
            profit += prices[prices.length - 1] - cost;
        }
        return profit;
    }
}
